package com.tax.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.template.TemplateException;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.tax.common.pdf.DuizhangDomain;
import com.tax.common.pdf.PageEvent;
import com.tax.common.pdf.YqTable;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ExportController {


    @RequestMapping(value = "/export/test",method= RequestMethod.GET)
    public void test(HttpServletResponse response) {
        try {
            response.setHeader("Content-Disposition", "attachment; filename=abc.pdf");
            OutputStream outputStream = response.getOutputStream();
            //模板路径，放到项目里用这个ClassPathResource
            ClassPathResource classPathResource = new ClassPathResource("template/tax_template.pdf");
            InputStream inputStream = classPathResource.getInputStream();
            PdfReader reader = new PdfReader(inputStream);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PdfStamper ps = new PdfStamper(reader, bos);

            //设置字体
            final BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<>();
            fontList.add(font);

            //提取表单,这个是模板画好的文本框
            AcroFields s = ps.getAcroFields();
            s.setSubstitutionFonts(fontList);
            s.setFieldProperty("text1","textfont",font,null);
            s.setField("text1", "这里是社会信用代码");
            s.setField("text2", "这里是企业名称");
            s.setField("text_2020", "text_2020");
            s.setField("text_2020_1", "text_2020_1");


            double[][] data = new double[][]{
                    {120,22,22,425,6,82,122,524,76,325,324,10}
            };
            String[] rowKeys = { "" };
            String[] columnKeys = { "2021/01","2021/02","2021/03","2021/04","2021/05","2021/06","2021/07","2021/08","2021/09","2021/10","2021/11","2021/12", };
            CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
            JFreeChart chart = ChartFactory.createLineChart(
                    "Example", // 图标题
                    "Year", // x轴标题
                    "Schools Count", // y轴标题
                    dataset, //数据集
                    PlotOrientation.VERTICAL, //图表方向
                    false, true, false);

            String chartName = "D:/spacework/tax/src/main/resources/template/a.png";
            FileOutputStream fos_jpg = new FileOutputStream(chartName);
            ChartUtilities.writeChartAsPNG(fos_jpg,chart,100,200);

            //添加图片
            PdfContentByte cb = ps.getOverContent(2);
            //按场合
            Rectangle acj = s.getFieldPositions("a_b").get(0).position;
            Image acjImage = Image.getInstance(chartName);
            //Image acjImage = Image.getInstance("https://pics5.baidu.com/feed/e1fe9925bc315c60d0a356da57ae1e18495477f8.png@f_auto?token=7809bc63cf1e4bf39552d792cdca029d");
            // 设根据域大小设置缩放图片
            acjImage.scaleToFit(acj.getWidth(), 200);
            // 设置居中
            acjImage.setAlignment(Image.MIDDLE);
            // 绝对定位
            acjImage.setAbsolutePosition(acj.getLeft(),acj.getBottom());
            cb.addImage(acjImage);


            ps.setFormFlattening(true);
            ps.close();

            /*reader = new PdfReader(bos.toByteArray());
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, outputStream);
            document.open();
            for (int i=1; i<=reader.getNumberOfPages(); i++) {
                PdfImportedPage importPage = copy.getImportedPage(reader, i);
                copy.addPage(importPage);
            }*/



            //*******************填充编辑好后的pdf**************
            reader = new PdfReader(bos.toByteArray());
            //Rectangle pageSize = reader.getPageSize(1);
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            writer.setPageEvent(new PageEvent());




            // 打开文档
            document.open();
            PdfContentByte cbUnder = writer.getDirectContentUnder();

            document.open();
            for (int i=1; i<=reader.getNumberOfPages(); i++) {
                if (i != 1) {
                    document.newPage();
                }
                PdfImportedPage pageTemplate = writer.getImportedPage(reader, i);
                cbUnder.addTemplate(pageTemplate, 0, 0);
            }



            document.close();
            outputStream.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }


    public static CategoryDataset getBarData(double[][] data, String[] rowKeys,String[] columnKeys){
        return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);
    }


    //为一个表格添加内容
    public PdfPCell createSetCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setPhrase(new Phrase(value, font));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        return cell;
    }


    //添加表格
    public void createTable(PdfWriter writer, Document document) throws DocumentException, IOException {

        PdfPTable table = new PdfPTable(new float[]{30, 80, 50, 50, 50});
        table.setTotalWidth(520);
        table.setPaddingTop(100);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
        table.writeSelectedRows(0, -1, 500, 800, writer.getDirectContentUnder());
        //每页都显示表头,输入几就是第几行的表头固定
        table.setHeaderRows(1);
        table.setHeaderRows(2);

        //定义数据的字体
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font textFont = new Font(baseFont, 10, Font.NORMAL);

        //表头信息
        PdfPCell heandCell = new PdfPCell();
        heandCell.setRowspan(1);
        heandCell.setColspan(5);
        heandCell.setFixedHeight(30);
        heandCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        heandCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        heandCell.setPhrase(new Phrase("对账情况表", textFont));
        heandCell.setPaddingTop(300);
        table.addCell(heandCell);

        //表字段
        String title[] = {"序号", "机构", "已对账", "未对账", "对账率%"};
        for (int i = 0; i < title.length; i++) {
            PdfPCell heardCell = new PdfPCell();
            heardCell.setRowspan(1);
            heardCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            heardCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            heardCell.setPhrase(new Phrase(title[i], textFont));
            heardCell.setMinimumHeight(20);
            table.addCell(heardCell);

        }


        //列表数据

        java.util.List<DuizhangDomain> duizhangDomains = new ArrayList<>();
        for (int i = 1; i <= 250; i++) {
            DuizhangDomain duizhangDomain = new DuizhangDomain();
            duizhangDomain.setJg("机构" + i).setYdz(i).setWdz(i).setDzl(new BigDecimal(i));
            duizhangDomains.add(duizhangDomain);
        }

        for (int i = 0; i < duizhangDomains.size(); i++) {
            PdfPCell setCell1 = createSetCell((i + 1) + "", textFont);
            PdfPCell setCell2 = createSetCell(duizhangDomains.get(i).getJg(), textFont);
            PdfPCell setCell3 = createSetCell(duizhangDomains.get(i).getYdz().toString(), textFont);
            PdfPCell setCell4 = createSetCell(duizhangDomains.get(i).getWdz().toString(), textFont);
            PdfPCell setCell5 = createSetCell(duizhangDomains.get(i).getDzl() + "%", textFont);
            table.addCell(setCell1);
            table.addCell(setCell2);
            table.addCell(setCell3);
            table.addCell(setCell4);
            table.addCell(setCell5);
        }
        document.add(table);
    }


    public void createTableYq(PdfWriter writer, Document document) throws DocumentException, IOException {

        PdfPTable table = new PdfPTable(new float[]{80, 50});
        table.setTotalWidth(520);
        table.setPaddingTop(500);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
        table.writeSelectedRows(0, -1, 500, 800, writer.getDirectContentUnder());
        //每页都显示表头,输入几就是第几行的表头固定
        table.setHeaderRows(2);
        table.setHeaderRows(3);

        //定义数据的字体
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font textFont = new Font(baseFont, 10, Font.NORMAL);

        //表头信息
        PdfPCell heandCell = new PdfPCell();
        heandCell.setRowspan(1);
        heandCell.setColspan(2);
        heandCell.setFixedHeight(30);
        heandCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        heandCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        heandCell.setPhrase(new Phrase("逾期表", textFont));
        table.addCell(heandCell);

        //表字段
        String title[] = {"机构名称", "逾期数"};
        for (int i = 0; i < title.length; i++) {
            PdfPCell heardCell = new PdfPCell();
            heardCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            heardCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            heardCell.setPhrase(new Phrase(title[i], textFont));
            heardCell.setMinimumHeight(20);
            table.addCell(heardCell);
        }

        //列表数据

        List<YqTable> yqTables = new ArrayList<>();
        for (int i = 1; i <= 1000; i++) {
            YqTable yq = new YqTable();
            yq.setJg("逾期机构" + i).setYqs(i);
            yqTables.add(yq);
        }

        for (int i = 0; i < yqTables.size(); i++) {
            PdfPCell setCell2 = createSetCell(yqTables.get(i).getJg(), textFont);
            PdfPCell setCell3 = createSetCell(yqTables.get(i).getYqs().toString(), textFont);
            table.addCell(setCell2);
            table.addCell(setCell3);
        }
        document.add(table);
    }

    /**
     * 创建表格跟表格之间的空白间隔
     */
    public void createBlankTable(PdfWriter writer, Document document, BaseFont font, int height) throws DocumentException {
        PdfPTable table = new PdfPTable(new float[]{30});
        table.setTotalWidth(520);
        table.setPaddingTop(500);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
        table.writeSelectedRows(0, -1, 500, 800, writer.getDirectContentUnder());
        Font textFont = new Font(font, 10, Font.NORMAL);
        PdfPCell cell = new PdfPCell(new Paragraph(" ", textFont));

        cell.setHorizontalAlignment(Element.ALIGN_LEFT);

        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);

        cell.setBorder(Rectangle.NO_BORDER);
        cell.setFixedHeight(height);

        cell.setColspan(1);

        table.addCell(cell);
        document.add(table);
    }

}
